<template>
	<div>
		<AplidForm v-model="formModel" v-if="!loading" v-bind="formConfig" @submit="onSubmit"></AplidForm>
	</div>
</template>

<script setup lang="ts">
import apiMod from '@/apiMod/index'
import { ElMessage } from 'element-plus'
import { useDateFormat } from '@vueuse/core'
const props = defineProps<{
	nowRowData: any
}>()
const emit = defineEmits(['refresh'])

const formModel: any = ref({})

const formConfig = ref({
	inline: false,
	showBtn: true,
	labelPosition: 'top',
	labelWidth: '120px',
	column: [],
})

const loading = ref(false)

const onSubmit = (form, done) => {
	let baseApi = formModel.value.id ? 'view_tableItem_edit' : 'view_tableItem_add'
	const query = {
		id: undefined,
		tableTemplateId: props.nowRowData.tableTemplateId,
		itemData: JSON.stringify(form),
		fieldId: props.nowRowData.id,
		fieldName: props.nowRowData.taskName,
		result: form.result,
		taskId: props.nowRowData.taskId,
	}
	if (form.id) {
		query.id = form.id
	}
	apiMod[baseApi](query)
		.then(() => {
			const evaluateTime = useDateFormat(new Date(), 'YYYY-MM-DD HH:mm:ss')
      console.log(evaluateTime)
			apiMod
				.view_pbHazardAssessment_edit({
					id: props.nowRowData.id,
					result: form.result,
					status: 1,
					evaluateTime:evaluateTime.value,
				})
				.then((res) => {
					emit('refresh')
				})

			ElMessage.success('操作成功')
			done(form)
		})
		.catch(() => {
			done()
		})
}
const getInitData = () => {
	loading.value = true
	apiMod
		.view_tableItem_list({
			fieldId: props.nowRowData.id,
			tableTemplateId: props.nowRowData.tableTemplateId,
		})
		.then((res) => {
			if (res.data.length == 1) {
				const item = res.data[0] || {}
				formModel.value = JSON.parse(item.itemData)
				formModel.value.id = item.id
			}
		})

	apiMod
		.view_tableTemplate_id(props.nowRowData.tableTemplateId)
		.then((res) => {
			loading.value = false
			const config = res.data?.jsonStr || {}
			console.log(config, 'config.column')
			formConfig.value.column = [
				...config.column,
				{
					label: '评估结果',
					prop: 'result',
					type: 'select',
					span: 24,
					dicData: [
						{ label: '合格', value: '合格' },
						{ label: '整改', value: '整改' },
					],
				},
			]
			console.log(formConfig.value.column, 'formConfigformConfig')
			formConfig.value.labelPosition = config.labelPosition
		})
		.catch(() => {
			loading.value = false
		})
}

onMounted(() => {
	getInitData()
})
</script>

<style scoped></style>
